package com.example.jcservice.service;

import com.dtflys.forest.http.ForestResponse;
import com.dtflys.forest.springboot.annotation.ForestScan;
import com.example.jcservice.client.JcYkt;
import com.example.jcservice.stType.Resive.Ykt.ShopImage;
import com.example.jcservice.stType.Resive.Ykt.ShopName;
import com.example.jcservice.stType.Resive.Ykt.YktRecords;
import com.example.jcservice.stType.Resive.Ykt.YktUserInfo;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Service
@ForestScan(basePackages = "com/example/jcservice/client")
public class YktService {
    @Resource//依赖注入写法
    private JcYkt ykt;

    /**
     * 模拟登录一卡通方法
     * */
    public YktUserInfo login(String username, String password) {
        String status;
        YktUserInfo Info = new YktUserInfo();

        //调用接口有参构造方法登录一卡通
        String userInfo = ykt.getInfo(username,password);
        System.out.println(userInfo);

        if (userInfo.equals("erro#账户密码存在问题，输入的密码与数据库中的密码不一样 （密码不对）")){
            System.out.println("密码错误\n\n");
            status = "密码错误";
            Info.setLoginStatus(status);

            return Info;
        }else if (userInfo.equals("erro#无效的校园卡账户账号")){
            status = "账户错误";
            Info.setLoginStatus(status);
            return Info;
        }else {
            status = "登录正常";
            Info.setLoginStatus(status);

            //个人信息
            Document document = Jsoup.parse(userInfo);
            Elements elements = document.select("td");

            Element uname = elements.get(3);//姓名
            Element uClass = elements.get(7);//班级
            Element state = elements.get(11);//状态
            Element money = elements.get(13);//剩余金额
            Element limitMoney = elements.get(19);//单日限额
            Element bankCard = elements.get(31);//银行卡号

            String un = uname.toString();
            String uc = uClass.toString();
            String us = state.toString();
            String um = money.toString();
            String ul = limitMoney.toString();
            String bc = bankCard.toString();

            //java 字符串截取
            String userName = un.substring(un.indexOf("<td>") + 4, un.indexOf("</td>"));
            String userClass = uc.substring(uc.indexOf("<td>") + 4, uc.indexOf("</td>"));
            String userState = us.substring(us.indexOf("<td>") + 4, us.indexOf("</td>"));
            String userMoney = um.substring(um.indexOf("<td>") + 4, um.indexOf("</td>"));
            String userLimitMoney = ul.substring(ul.indexOf("<td>") + 4, ul.indexOf("</td>"));
            String userBankcard = bc.substring(bc.indexOf("<td>") + 4, bc.indexOf("</td>"));


            System.out.println("姓名：" + userName + "\n一卡通状态：" + userState + "\n剩余金额:" + userMoney);


            Info.setUserName(userName);
            Info.setUserClass(userClass);
            Info.setState(userState);
            Info.setMoney(userMoney);
            Info.setLimitMoney(userLimitMoney);
            Info.setBankCard(userBankcard);

        }

        return Info;
    }

    /**
     * 获取一卡通消费记录方法
     * */
    @Resource
    private ShopName shopName;
    @Resource
    private ShopImage shopImage;

    YktRecords record = new YktRecords();
    ArrayList<String> YktRecordsInfo_String = new ArrayList();//用于存放第一步网页爬取的 String数据
    ArrayList<String> MachineInfo_String = new ArrayList();//用于存放第网页爬取的消费机器编号 String数据

    public YktRecords getRecords(String username, String password, String start, String end) {
        //方法开始必须清除上一次查询后各种集合缓存数据，不然会有各种错误
        YktRecordsInfo_String.clear();
        YktRecords.recordsInfos.clear();
        MachineInfo_String.clear();

        //定义查询第二笔消费记录开始的循环中间变量
        int count1=0;
        int count2=1;
        int count3=2;
        int count4=3;
        int count5=4;

        //forest模拟登录
        ForestResponse userRecords = ykt.getRecords (username,password,start,end);
        //jsoup获取消费记录源码
        Document document = Jsoup.parse(userRecords.getContent());
        Elements elements = document.select("td");
        //分离出机器编号语句jsoup单独写法，按照标签里面属性值获取内容
        Elements elements1 = document.getElementsByAttribute("onclick");

        for (int n=0;n<elements.size();n++){
            Element textContent = elements.get(n);
            String Content = textContent.text();
            YktRecordsInfo_String.add(Content);
        }

        for (int i=0;i<YktRecordsInfo_String.size()/5;i++){
            //每一次循环创建new一个消费记录对象，存放每一笔消费记录详情
            YktRecords.YktRecordsInfo c = new YktRecords.YktRecordsInfo();

            //jsoup提取消费机器编码html语句单独方法
            Element textContent = elements1.get(i);
            String Content = textContent.toString();
            MachineInfo_String.add(Content);
            //以 @ 字符分割字符串获取 机器编号 字符串===》set实体类
            //未分割源码示例 <td class="cen" align="center"><a width="100%" href="javascript:;" onclick="zhuandaoxiangxi('2021-06-06 05:29:46@独立售饭@9.00@75.40@0.00@01-07-088-五食堂@@0000@0.00')">详情</a></td>
            String b[]=MachineInfo_String.get(i).split("@");
            c.setMachine(b[5]);//取数组里面第五个数据,set进商铺机器
            c.setShop(shopName.getShopName(b[5]));//拿key读value值，HashMap为单独读一个类，set进实体类的Shop属性
            c.setShopImage(shopImage.getShopImage(b[5]));

            //第一笔消费单独方法
            if (i==0){
                //获取 消费类型 字符串，set实体类
                c.setType(YktRecordsInfo_String.get(i));
                //获取 消费金额 字符串，set实体类
                c.setSpentMoney(YktRecordsInfo_String.get(i+1));
                //获取 剩余金额 字符串，set实体类
                c.setSurplusMoney(YktRecordsInfo_String.get(i+2));
                //获取 消费时间 字符串，set实体类
                c.setTime(YktRecordsInfo_String.get(i+3));
            }
            //第二笔消费开始方法
            else {
                //设置中间变量，用for循环定位第二笔消费开始的每个属性值
                count1=count1+5;
                count2=count2+5;
                count3=count3+5;
                count4=count4+5;
                count5=count5+5;
                //获取 消费类型 字符串，set实体类
                c.setType(YktRecordsInfo_String.get(count1));
                //获取 消费金额 字符串，set实体类
                c.setSpentMoney(YktRecordsInfo_String.get(count2));
                //获取 剩余金额 字符串，set实体类
                c.setSurplusMoney(YktRecordsInfo_String.get(count3));
                //获取 消费时间 字符串，set实体类
                c.setTime(YktRecordsInfo_String.get(count4));
            }
            //将每一次循环new的消费记录详情对象，存进YktRecords实体类的 recordsInfos 集合中
            YktRecords.recordsInfos.add(c);
        }
        return record;
    }

    /**
     * 一卡通挂失方法
     *
     * @return*/
    public String YktGs(String username, String password, String state){
        String result = null;

            if (state.equals("0")) {
                Map<String, String> GsQuery = new HashMap<String, String>();
                GsQuery.put("ty", "8");//业务编号，8代表挂失，26代表解除挂失
                GsQuery.put("user", username);
                GsQuery.put("pass", password);
                GsQuery.put("school", "1000");
                GsQuery.put("level", "1");

                ForestResponse response = ykt.yktGs(GsQuery);
                if (response.getContent().equals("OK")){
                    result = "挂失成功";
                }
                else {
                    result = "网络出错";
                }
            }else {
                Map<String, String> JgQuery = new HashMap<String, String>();
                JgQuery.put("ty", "26");//业务编号，8代表挂失，26代表解除挂失
                JgQuery.put("user", username);
                JgQuery.put("pass", password);
                JgQuery.put("school", "1000");
                JgQuery.put("level", "1");

                ForestResponse response = ykt.yktGs(JgQuery);
                if (response.getContent().equals("OK")){
                    result = "解除挂失成功";
                }else {
                    result = "网络出错";
                }
            }

            return result;

    }

    /**
     * 一卡通设置当日消费限额方法
     *
     * @return*/
    public String YktLimit(String username, String password, String money){
         String result = null;
        Map<String, String> LimitQuery = new HashMap<String, String>();
        LimitQuery.put("ty", "5");//业务编号，8代表挂失，26代表解除挂失
        LimitQuery.put("user", username);
        LimitQuery.put("pass", password);
        LimitQuery.put("school", "1000");
        LimitQuery.put("rixian", money);
        LimitQuery.put("xian1", "9999.99");
        LimitQuery.put("xian2", "9999.99");
        LimitQuery.put("xian3", "9999.99");
        LimitQuery.put("xian4", "9999.99");
        LimitQuery.put("xian5", "9999.99");
        LimitQuery.put("xian6", "9999.99");
        LimitQuery.put("xian7", "9999.99");
        LimitQuery.put("xian0", "9999.99");
        LimitQuery.put("level", "1");

        ForestResponse response = ykt.yktLimit(LimitQuery);
        if (response.getContent().equals("OK")){
            result = "设置成功";
        }else {
            result = "网络出错";
        }
        return result;

    }

}
